<?php
declare (strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\Order as OrderM;
use app\model\Promotion;
use app\model\Supplier as SupplierM;
use app\model\TblAttractfansProxy;
use app\repository\GoodsRepository;
use think\annotation\route\Group;
use think\annotation\Route;
use \app\model\User as UserM;
use app\middleware\CheckAdmin;
use think\annotation\route\Middleware;
use think\facade\Db;

/**
 * 订单
 * Class User
 * @package app\controller\admin
 * @Group("admin/order")
 * @Middleware({CheckAdmin::class})
 */
class Order extends BaseController
{

    /**
     * 获取订单列表
     * @Route("list", method="GET")
     */
    public function list()
    {
        $uid = input('get.uid', '', 'int');
        $page = input('page', 1, 'int');
        $limit = input('limit', 50, 'int');
        $startTime = input('startTime','','string');
        $endTime = input('endTime','','string');
        $tradeStatus = input('tradeStatus',null,'int');
        $goodsName = input('goodsName','','string');
        $tradeId = input('tradeId','','int');
        $supplierName = input('supplierName','','string');
        $orderNo = input('orderNo','','string');
        $buyPhone = input('buyPhone','','string');
        $contactPhone = input('contactPhone','','string');
        $cardNumber = input('cardNumber','','string');
        $promotionName = input('promotionName','','string');//二级分销商
        $parentPromotionName = input('parentPromotionName','','string');//一级分销商
        $trackingCode = input('trackingCode','','string');
        $merchantId= input('merchantId','','int');
        $goodsId = input('goodsId','','int');

        $where = [];
        if (!empty($parentPromotionName)) {
            $onePromotion = (new Promotion())->where(['subordinate_name'=>$parentPromotionName,'parent_user_id' => 1])->find();
            if (empty($onePromotion)) {
                return json_ok([],200);
            }

            $promotionIds = (new Promotion())->where('user_id',$onePromotion['user_id'])->whereOr('parent_user_id' , $onePromotion['user_id'])->column('user_id');

            $where[] = ['o.promotion_id', 'in', $promotionIds];
        }

        if (!empty($promotionName)) {
            $onePromotion = (new Promotion())->where('subordinate_name',$promotionName)->where('parent_user_id','<>', 1)->find();
            if (empty($onePromotion)) {
                return json_ok([],200);
            }

            $where[] = ['o.promotion_id', '=', $onePromotion['user_id']];
        }

        if (!empty($trackingCode)) {
            $where[] = ['o.tracking_code', '=', $trackingCode];
        }

        if (!is_null($tradeStatus)) {
            $where[] = ['o.status', '=', $tradeStatus];
        }


        if (!empty($startTime)) {
            $where[] = ['o.create_time', '>', strtotime($startTime)];
        }

        if (!empty($endTime)) {
            $where[] = ['o.create_time', '<', strtotime($endTime) + 86400];
        }

        if (!empty($goodsName)) {
            $where[] = ['g.goods_title', '=', $goodsName];
        }

        if (!empty($tradeId)) {
            $where[] = ['o.trade_id', '=', $tradeId];
        }

        if (!empty($supplierName)) {
            $where[] = ['s.name', '=', $supplierName];
        }

        if (!empty($orderNo)) {
            $where[] = ['o.order_no', '=', $orderNo];
        }

        if (!empty($buyPhone)) {
            $where[] = ['o.buy_phone', '=', $buyPhone];
        }

        if (!empty($contactPhone)) {
            $where[] = ['o.contact_phone', '=', $contactPhone];
        }

        if (!empty($cardNumber)) {
            $where[] = ['o.card_number', '=', $cardNumber];
        }

        if (!empty($merchantId)) {
            $where[] = ['o.merchant_id', '=', $merchantId];
        }

        if (!empty($goodsId)) {
            $where[] = ['o.goods_id', '=', $goodsId];
        }


        if (empty($uid)) {
            return json_error(10002);
        }
        $role = $this->request->sys_user->role;

        $userM = new UserM();
        $orderM = new OrderM();

        switch ($role) {
            case UserM::USER_ROLE_ADMIN://管理员
                $list = Db::name(OrderM::$_table)->alias('o')
                    ->field(['o.*','o.user_name','g.goods_title','s.name as supplier_name'])
                    ->join(UserM::$_table . ' u', 'u.id=o.promotion_id', 'left')
                    ->join(SupplierM::$_table . ' s', 'o.supplier_id=s.id', 'left')
                    ->join(\app\model\Goods::$_table . ' g', 'g.goods_id=o.goods_id', 'left')
                    ->where($where)
                    ->order('create_time', 'desc')
                    ->paginate(['page' => $page, 'list_rows' => $limit])->toArray();
//                echo Db::name(OrderM::$_table)->getLastSql();die;
                break;
            case UserM::USER_ROLE_FIRST://一级代理
                $userIds = $userM->where('id',$uid)->whereOr('parent_id', $uid)->column('id');
                $list = Db::name(OrderM::$_table)->alias('o')
                    ->where('promotion_id', 'in', $userIds)
                    ->field(['o.id','o.goods_id', 'o.trade_id', 'o.order_no','o.status','o.contact_phone','o.buy_phone','o.promotion_id','o.tracking_code','o.create_time','o.user_name','g.goods_title','o.recharge_date','o.activation_date','o.address'])
                    ->join(UserM::$_table . ' u', 'u.id=o.promotion_id', 'left')
                    ->join(\app\model\Goods::$_table . ' g', 'g.goods_id=o.goods_id', 'left')
                    ->order('create_time', 'desc')
                    ->where($where)
                    ->paginate(['page' => $page, 'list_rows' => $limit])
                    ->toArray();
                break;
            case UserM::USER_ROLE_SECOND://二级代理
                $list = Db::name(OrderM::$_table)->alias('o')
                    ->field(['o.id','o.order_no','o.goods_id','o.status','o.create_time','g.goods_title','o.recharge_date','o.activation_date'])
                    ->join(\app\model\Goods::$_table . ' g', 'g.goods_id=o.goods_id', 'left')
                    ->where('o.promotion_id', $this->request->sys_user->id)
                    ->where($where)
                    ->order('create_time', 'desc')
                    ->paginate(['page' => $page, 'list_rows' => $limit])->toArray();
                break;
        }


        return json_ok($list,200);
    }

    /**
     * 修改订单状态
     * @Route("editStatus", method="POST")
     */
    public function editStatus()
    {
        $status = input('post.status', '', 'int');
        $orderId = input('post.orderId', '', 'int');
        if (empty($status) || empty($orderId)) {
            return json_error(10002);
        }
        $role = $this->request->sys_user->role;
        if ($role) {
            return json_error(10014);
        }

        $oneOrder = (new OrderM())->where('id', $orderId)->find();
        if (empty($oneOrder)) {
            return json_error(10004);
        }
        $oneOrder->status = $status;
        $oneOrder->save();
        return json_ok([],200);

    }
}
